#! /bin/bash

#
# Collective Knowledge (CK)
#
# See CK LICENSE.txt for licensing details.
# See CK COPYRIGHT.txt for copyright details.
#
# Developer: Grigori Fursin
#

governer=conservative
if [ "$CK_CPU_FREQ_GOVERNOR" != "" ]; then
  governer=$CK_CPU_FREQ_GOVERNOR
fi

freqmin=cpuinfo_min_freq
freqmax=cpuinfo_max_freq
if [ "$CK_CPU_FREQ_FILE" != "" ]; then
  freqmin=$CK_CPU_FREQ_FILE
  freqmax=$CK_CPU_FREQ_FILE
fi

if [ "$CK_CPU_FREQ" != "" ]; then
  freqmin=$CK_CPU_FREQ
  freqmax=$CK_CPU_FREQ
fi

if [ "$CK_CPU_FREQ_MIN" != "" ]; then
  freqmin="$CK_CPU_FREQ_MIN"
fi

if [ "$CK_CPU_FREQ_MAX" != "" ]; then
  freqmax="$CK_CPU_FREQ_MAX"
fi

if [ "$1" != "" ]; then
  freqmin="$1"
  freqmax="$1"
fi

if [ "$2" != "" ]; then
  freqmax="$2"
fi

online=1
if [ "$CK_CPU_ONLINE" != "" ]; then
  online=$CK_CPU_ONLINE
fi

if [ "$online" == "1" ] ; then
  echo "    Bringing all CPU online ..."
  for cpudir in /sys/devices/system/cpu/cpu*
  do
    if [ -f "$cpudir/online" ] ; then
      echo $online | sudo tee $cpudir/online >/dev/null
    fi
  done
fi

for cpudir in /sys/devices/system/cpu/cpu*
do
  if [ -d "$cpudir/cpufreq" ] && [ -f "$cpudir/cpufreq/scaling_governor" ] ; then
    echo "*** Processing $cpudir ..."

    echo "    Setting $governer state ..."
    echo $governer | sudo tee $cpudir/cpufreq/scaling_governor >/dev/null

    # change $freqmin and $freqmax in a subshell
    (

    if ! [[ $freqmin =~ [0-9]+ ]]; then
      freqmin=$(cat $cpudir/cpufreq/$freqmin)
    fi

    if ! [[ $freqmax =~ [0-9]+ ]]; then
      freqmax=$(cat $cpudir/cpufreq/$freqmax)
    fi

    echo "    Setting min/max frequency=$freqmin/$freqmax ..."
    echo $freqmin | sudo tee $cpudir/cpufreq/scaling_min_freq >/dev/null
    echo $freqmax | sudo tee $cpudir/cpufreq/scaling_max_freq >/dev/null
    echo $freqmin | sudo tee $cpudir/cpufreq/scaling_min_freq >/dev/null
    echo $freqmax | sudo tee $cpudir/cpufreq/scaling_max_freq >/dev/null

    )

    echo "    Current frequency=$(cat $cpudir/cpufreq/scaling_cur_freq)"

    if [ "$online" == "0" -a "$cpudir" != "/sys/devices/system/cpu/cpu0" ]; then
      echo "    Bringing CPU offline ..."
      echo $online | sudo tee $cpudir/online >/dev/null
    fi
  fi
done
